package com.asset.dispoal.business.bsEvidenceRecognition.service.commom;

import com.asset.dispoal.business.match.dto.MatchRequest;
import com.asset.dispoal.business.merge.domain.db.mapper.MergeDownloadMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.redis.commands.IRedisExtCommands;

import java.util.Objects;

@Component
@Slf4j
public class EvidenceMergeResultCommand implements BaseCommand<MatchRequest, Result> {

    @Autowired
    private MergeDownloadMapper mergeDownloadMapper;
    @Autowired
    private IRedisExtCommands redisExtCommands;

    @Autowired
    private Environment environment;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(MatchRequest matchRequest) {
        String requestKey = matchRequest.getData().getRequestKey();
        redisExtCommands.hdel(6, "merge_before", requestKey);
        if (matchRequest.isFaild()) {
            mergeDownloadMapper.updateStateFileUrl(requestKey, null, "0");
            return Result.ok();
        }
        String responseKey = matchRequest.getData().getResponseKey();
        String notifyKey = responseKey + "_" + requestKey;
        String evidenceFileUrl = redisExtCommands.hget(6, "merge_notify_key", notifyKey);
        if (StringUtil.isNotEmpty(evidenceFileUrl)) {
            evidenceFileUrl = evidenceFileUrl.replace(Objects.requireNonNull(environment.getProperty("file.evidence.url")), "");
        }
        redisExtCommands.hdel(6, "merge_notify_key", notifyKey);
        mergeDownloadMapper.updateStateFileUrl(requestKey, evidenceFileUrl, "1");
        return Result.ok();
    }
}
